package bootstrap

import (
	"fmt"
	"os"
	"peilian-api/app/global/config"
	"peilian-api/app/global/databases"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/variable"
	"peilian-api/utils/sdk"
)

func checkOperatingEnvironment(filePath string) {
	if _, err := os.Stat(filePath); err != nil {
		fmt.Println(errors.ConfigYamlNotExists + err.Error())
	}
}

func init() {
	defer fmt.Println("离开 -> bootstrap/init() ")
	fmt.Println("进入 -> bootstrap/init() ")
	env := os.Getenv("ENV")
	if env == "" {
		env = "local"
	}
	fmt.Println("当前环境: -> ", env)
	filePath := variable.BasePath + fmt.Sprintf("/config/%s/config.yaml", env)
	checkOperatingEnvironment(filePath)

	var err error
	if variable.Config, err = config.InitConfig(filePath); err != nil {
		fmt.Println(errors.ConfigYamlParseFail + err.Error())
	}
	if variable.UfsConfig, err = sdk.InitUFile(variable.BasePath + "/config/ufs.json"); err != nil {
		fmt.Println(errors.UfsConfigJsonIsFail + err.Error())
		os.Exit(1)
	}

	if variable.DB.MySQL, err = databases.InitMySQL(); err != nil {
		fmt.Println(errors.DatabaseMySQLConnectionFail + err.Error())
		os.Exit(1)
	}
	databases.Migrate()

	if variable.DB.Redis, err = databases.InitRedis(); err != nil {
		fmt.Println(errors.DatabaseRedisConnectionFail + err.Error())
		os.Exit(1)
	}
	if err := loadDataToRedis(); err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

}
